package com.hzdracom.zhangnn.mainfestdemo;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 项目名称 MainfestDemo.
 * 包名 com.hzdracom.zhangnn.mainfestdemo
 * 创建者 zhangnn
 * 创建时间  2016/8/15 13:59.
 * 备注 ：权限工具类
 */
public class PermissionUtil {

/*    public static final String CALENDAR = "android.permission-group.CALENDAR";
    public static final String CAMERA = "android.permission-group.CAMERA";
    public static final String CONTACTS = "android.permission-group.CONTACTS";
    public static final String LOCATION = "android.permission-group.LOCATION";
    public static final String MICROPHONE = "android.permission-group.MICROPHONE";
    public static final String PHONE = "android.permission-group.PHONE";
    public static final String SENSORS = "android.permission-group.SENSORS";
    public static final String SMS = "android.permission-group.SMS";
    public static final String STORAGE = "android.permission-group.STORAGE";*/

    /** 请求权限分组 */

    /** 日历 */
    public static final String REQUEST_CALENDAR_GROUP = "android.permission-group.CALENDAR";
    /** 相机 */
    public static final String REQUEST_CAMERA_GROUP = "android.permission-group.CAMERA";
    /** 联系人 */
    public static final String REQUEST_CONTACTS_GROUP = "android.permission-group.CONTACTS";
    /** 地理位置 */
    public static final String REQUEST_LOCATION_GROUP = "android.permission-group.LOCATION";
    /** 麦克风 */
    public static final String REQUEST_MICROPHONE_GROUP = "android.permission-group.MICROPHONE";
    /** 手机状态 */
    public static final String REQUEST_PHONE_GROUP = "android.permission-group.PHONE";
    /** 传感器 */
    public static final String REQUEST_SENSORS_GROUP = "android.permission-group.SENSORS";
    /** 短信 */
    public static final String REQUEST_SMS_GROUP = "android.permission-group.SMS";
    /** 存储卡 */
    public static final String REQUEST_STORAGE_GROUP = "android.permission-group.STORAGE";

    /**
     * 请求权限
     * 因为6.0以后危险权限是按照群组来划分的，
     * 当某一个权限被授权时，跟它同组的其他权限也会被授权。
     */
    public static final String REQUEST_CALENDAR = "android.permission.READ_CALENDAR";
    public static final String REQUEST_CAMERA = "android.permission.CAMERA";
    public static final String REQUEST_CONTACTS = "android.permission.READ_CONTACTS";
    public static final String REQUEST_LOCATION = "android.permission.ACCESS_COARSE_LOCATION";
    public static final String REQUEST_MICROPHONE = "android.permission.RECORD_AUDIO";
    public static final String REQUEST_PHONE = "android.permission.READ_PHONE_STATE";
    public static final String REQUEST_SENSORS = "android.permission.BODY_SENSORS";
    public static final String REQUEST_SMS = "android.permission.READ_SMS";
    public static final String REQUEST_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";

    /**
     * 权限请求码
     */
    public static final int REQUEST_CALENDAR_CODE = 0x00;
    public static final int REQUEST_CAMERA_CODE = 0x01;
    public static final int REQUEST_CONTACTS_CODE = 0x02;
    public static final int REQUEST_LOCATION_CODE = 0x03;
    public static final int REQUEST_MICROPHONE_CODE = 0x04;
    public static final int REQUEST_PHONE_CODE = 0x05;
    public static final int REQUEST_SENSORS_CODE = 0x06;
    public static final int REQUEST_SMS_CODE = 0x07;
    public static final int REQUEST_STORAGE_CODE = 0x08;

    /* 权限组具体权限 */
/*  Manifest.permission-group.CALENDAR
    Manifest.permission.READ_CALENDAR
    Manifest.permission.WRITE_CALENDAR*/

/*  Manifest.permission-group.CAMERA
    Manifest.permission.CAMERA*/

/*  Manifest.permission-group.CONTACTS
    Manifest.permission.WRITE_CONTACTS
    Manifest.permission.GET_ACCOUNTS
    Manifest.permission.READ_CONTACTS*/

/*  Manifest.permission_group.LOCATION
    Manifest.permission.ACCESS_FINE_LOCATION;
    Manifest.permission.ACCESS_COARSE_LOCATION;*/

/*  Manifest.permission_group.MICROPHONE
    Manifest.permission.RECORD_AUDIO;*/

/*  Manifest.permission_group.PHONE;
    Manifest.permission.READ_CALL_LOG
    Manifest.permission.READ_PHONE_STATE
    Manifest.permission.CALL_PHONE
    Manifest.permission.WRITE_CALL_LOG
    Manifest.permission.USE_SIP
    Manifest.permission.PROCESS_OUTGOING_CALLS*/

/*  Manifest.permission_group.SENSORS
    Manifest.permission.BODY_SENSORS*/


/*  Manifest.permission_group.SMS;
    Manifest.permission.READ_SMS
    Manifest.permission.RECEIVE_WAP_PUSH;
    Manifest.permission.RECEIVE_MMS;
    Manifest.permission.RECEIVE_SMS;
    Manifest.permission.SEND_SMS;
    Manifest.permission.READ_CELL_BROADCASTS;*/

/*  Manifest.permission_group.STORAGE
    Manifest.permission.READ_EXTERNAL_STORAGE;
    Manifest.permission.WRITE_EXTERNAL_STORAGE;*/

    /**
     * 检测应用申请的权限是否被授权，该方法适用于 buildVision 23级以上的版本
     *
     * @param context
     * @param permission
     * @return true 该权限已经被授权， false该权限没有被授权
     */
    public static boolean checkPermission(Context context, String permission) {
        // PERMISSION_GRANTED = 0 被授权
        // PERMISSION_DENIED = -1 没有被授权;
        return ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 判断权限是否被授权，该方法适用于 buildVision 23级以上的版本
     *
     * @param context
     * @param permissions
     * @return true 全部权限都已经授权，false 至少有一个权限没有授权
     */
    public static boolean checkPermissions(Context context, String... permissions) {
        for (String mPermission : permissions) {
            if (!checkPermission(context, mPermission))
                return false;
        }
        return true;
    }


    /**
     * 是否需要显示请求权限的弹窗，默认返回false，
     * 如果用户点击拒绝但没有记住选择则返回true，申请权限的时候，请求流程正常执行
     * 如果用户点击拒绝且选择记住选择，则返回false，申请权限的时候，请求结果直接返回拒绝
     *
     * @param activity
     * @param permission
     * @return
     */
    public static boolean shouldShowRequest(Activity activity, String permission) {
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
    }


    /**
     * 请求权限
     * 一般情况下请求相机的时候，需要同时申请地理位置权限和麦克风权限，
     * 地理位置权限是为了给照片添加坐标信息，
     * 麦克风权限是为了录像的时候，同时把声音录制进去
     *
     * @param activity
     * @param requestCode
     * @param permissions
     */
    public static void requestPermissions(Activity activity, int requestCode, String... permissions) {
        ActivityCompat.requestPermissions(activity, permissions, requestCode);
    }

    /**
     *显示缺失权限提示
     */
    public static void showMissingPermissionDialog(final Context context, final IPermissionListener listener) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);
        builder.setCancelable(false);

        //拒绝关闭弹窗，并退出应用
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                listener.cancel();
            }
        });
        //设置，跳转到手机权限设置页面
        builder.setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                listener.set();
                startAppSettings(context);
            }
        });

        builder.show();
    }

    /**
     * 启动手机权限设置
     * @param context
     */
    public static void startAppSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    interface IPermissionListener {
        void cancel();

        void set();
    }

    /**
     * 应用是否有某一权限,该方法兼容 buildVision 小于23的版本
     *
     * @param context
     * @param op      权限所代表的int值
     * @return 0 有 1 没有 -1出错
     */
    private static int checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
//            Object object = context.getSystemService("appops");
            Object object = context.getSystemService(Context.APP_OPS_SERVICE);
            Class c = object.getClass();
            try {
                Class[] cArg = new Class[3];
                cArg[0] = int.class;
                cArg[1] = int.class;
                cArg[2] = String.class;
                Method lMethod = c.getDeclaredMethod("checkOp", cArg);
                return (Integer) lMethod.invoke(object, op, Binder.getCallingUid(), context.getPackageName());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }
}
